<template>
  <div>
    <!-- 访客建档 -->
    <div
      class="change_customer"
      :style="{
        'margin-top': marginTop + 'vh',
      }"
    >
      <el-card class="qr">
        <template #header>
          <div class="title">使用微信扫码</div>
        </template>
        <!-- <img
          src="https://file.supore.cn/1752895549欠揍qr.png"
          alt=""
          class="max-h-[60vh] mx-auto mt-[2rem]"
        /> -->
        <qrcode-vue
          :value="qrUrl"
          :margin="1"
          :size="qrSize"
          class="max-h-[60vh] mx-auto mt-[2rem]"
        />
      </el-card>

      <el-card class="customer_info relative">
        <template #header>
          <div class="title">
            {{ isSelectCustomer == 1 ? "新增客户" : "客户信息" }}
          </div>
        </template>

        <el-scrollbar style="height: calc(100vh - 17.5rem)">
          <el-form
            :model="addForm"
            ref="addFormRef"
            label-width="100px"
            class="addForm"
            :rules="rules"
            inline
          >
            <el-descriptions
              class="w-full"
              border
              :column="2"
              v-if="isSelectCustomer == 1"
            >
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label" :data-required="true">
                    <span>姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名</span>
                    <span class="star">*</span>
                  </div>
                </template>
                <el-form-item prop="customerName">
                  <el-input
                    v-model="addForm.customerName"
                    clearable
                    placeholder="请输入姓名"
                  />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item :rowspan="3" align="center">
                <template #label>
                  头&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;像
                </template>
                <UploadImage v-model="addForm" fileName="headUrl" />

                <!-- <el-image
                  style="width: 100px; height: 100px"
                  src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                /> -->
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    <span>联系方式</span>
                    <span class="star">*</span>
                  </div>
                </template>
                <el-form-item prop="customerTel">
                  <el-input
                    v-model="addForm.customerTel"
                    clearable
                    placeholder="请输入联系方式"
                  />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    <span>性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别</span>
                    <span class="star">*</span>
                  </div>
                </template>
                <el-form-item prop="sex">
                  <el-radio-group v-model="addForm.sex">
                    <el-radio-button label="男" :value="1" />
                    <el-radio-button label="女" :value="2" />
                  </el-radio-group>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    <span>出生日期</span>
                    <span class="star">*</span>
                  </div>
                </template>
                <el-form-item prop="birthday">
                  <el-date-picker
                    v-model="addForm.birthday"
                    type="date"
                    placeholder="请选择日期"
                    format="YYYY-MM-DD"
                    value-format="x"
                    class="input"
                  />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址
                  </div>
                </template>
                <el-form-item prop="address">
                  <el-input
                    v-model="addForm.address"
                    clearable
                    placeholder="请输入地址"
                  />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    职&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;业
                  </div>
                </template>
                <el-form-item prop="occupationName">
                  <el-select
                    v-model="addForm.occupationName"
                    clearable
                    filterable
                    placeholder="请选择职业"
                  >
                    <el-option
                      v-for="item in occupationList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">用眼距离</div>
                </template>
                <el-form-item prop="eyeUsageDistanceName">
                  <el-select
                    v-model="addForm.eyeUsageDistanceName"
                    clearable
                    filterable
                    placeholder="请选择用眼距离"
                  >
                    <el-option
                      v-for="item in eyeUsageDistanceList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">工作环境</div>
                </template>

                <el-form-item prop="workEnvName">
                  <el-select
                    v-model="addForm.workEnvName"
                    clearable
                    filterable
                    placeholder="请选择工作环境"
                  >
                    <el-option
                      v-for="item in workEnvList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>

            <el-descriptions class="w-full" border :column="2" v-else>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label" :data-required="true">
                    <span>姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名</span>
                  </div>
                </template>
                <el-form-item prop="customerName">
                  <el-text truncated>
                    {{ addForm.customerName }}
                  </el-text>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item :rowspan="3" align="center">
                <template #label>
                  头&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;像
                </template>

                <el-image class="w-[6rem] h-[6rem]" :src="addForm.headUrl" />
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    <span>联系方式</span>
                  </div>
                </template>
                <el-form-item prop="customerTel">
                  {{ addForm.customerTel }}
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    <span>性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别</span>
                  </div>
                </template>
                <el-form-item prop="sex">
                  {{ addForm.sex == 1 ? "男" : addForm.sex == 2 ? "女" : "" }}
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    <span>出生日期</span>
                  </div>
                </template>
                <el-form-item prop="birthday">
                  {{ $initTime(addForm.birthday) }}
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址
                  </div>
                </template>
                <el-form-item prop="address">
                  <span>
                    {{ addForm.address }}
                  </span>
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">
                    职&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;业
                  </div>
                </template>
                <el-form-item prop="occupationName">
                  {{ addForm.occupationName }}
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">用眼距离</div>
                </template>
                <el-form-item prop="eyeUsageDistanceName">
                  {{ addForm.eyeUsageDistanceName }}
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item align="center">
                <template #label>
                  <div class="label">工作环境</div>
                </template>
                <el-form-item prop="workEnvName">
                  {{ addForm.workEnvName }}
                </el-form-item>
              </el-descriptions-item>
            </el-descriptions>
          </el-form>
        </el-scrollbar>

        <div
          class="absolute bottom-[1rem] right-[1rem]"
          v-if="isSelectCustomer == 1"
        >
          <el-button
            type="danger"
            class="w-[5rem]"
            icon="Close"
            @click="handleRemove"
            >清空</el-button
          >
          <el-button
            type="primary"
            class="w-[5rem]"
            icon="Check"
            @click="handleSubmit"
            :loading="loading"
          >
            {{ loading ? "保存中..." : "保存" }}
          </el-button>
        </div>
        <div class="absolute bottom-[1rem] right-[1rem]" v-else>
          <el-button
            type="info"
            class="w-[5rem]"
            icon="Edit"
            @click="handleEdit"
            >修改</el-button
          >
          <el-button
            type="primary"
            class="w-[5rem]"
            icon="Check"
            @click="nextStep"
            :loading="loading"
          >
            下一步
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import QrcodeVue from "qrcode.vue";
import UploadImage from "@/components/UploadImage.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  CreateCustomerByPc,
  ListCustomerOccupation,
  ListCustomerEyeUsageDistance,
  ListCustomerWorkEnv,
  GetUserInfo,
} from "../../../../../wailsjs/go/api/CustomerApi.js";
import { UploadFile } from "../../../../../wailsjs/go/api/FileSystem.js";

const router = useRouter();
const useStore = useUserStore();
const { isSelectCustomer } = storeToRefs(useStore);

onMounted(async () => {
  marginTop.value = 70 / 50;

  getOccupationList();
  getEyeUsageDistanceList();
  getWorkEnvList();
  getUserInfo();

  addForm.value = cloneDeep(useStore.customerInfo);
});

const qrSize = ref(300);
const updateSize = () => {
  let fontSize = parseInt(getComputedStyle(document.body).fontSize);
  qrSize.value = fontSize * 14;
};
window.addEventListener("resize", () => {
  updateSize();
});

const addFormRef = ref(null);
const addForm = ref({
  customerName: "",
  customerTel: "",
  sex: null,
  birthday: null,
  address: "",
  occupationName: "",
  eyeUsageDistanceName: "",
  workEnvName: "",
});
// 清空
const handleRemove = () => {
  ElMessageBox.confirm("您确定要清空客户建档信息吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    addFormRef.value.resetFields();
    useStore.updateCustomerInfo({
      customerName: "",
      customerTel: "",
      sex: null,
      birthday: null,
    });
  });
};
// 保存
const loading = ref(false);
const handleSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return ElMessage.warning("请输入正确的信息");
    loading.value = true;
    handleApiResponse(() => CreateCustomerByPc(addForm.value)).then((res) => {
      if (res.code == 0) {
        ElMessage.success("建档成功");
        useStore.updateCustomerInfo(addForm.value);
        useStore.updateIsSelectCustomer(2);
      }
      loading.value = false;
    });
  });
};

// 返回上一步 修改
const handleEdit = () => {
  useStore.updateIsSelectCustomer(1);
};
// 下一步
const nextStep = () => {
  router.push({ name: "face_scan" });
};

const rules = ref({
  customerName: [{ required: true, message: "请输入姓名" }],
  customerTel: [
    { required: true, message: "请输入联系方式" },
    {
      pattern: /^[1-9]\d{10}$/,
      message: "请输入正确的联系方式",
    },
  ],
  sex: [{ required: true, message: "请选择性别" }],
  birthday: [{ required: true, message: "请选择出生日期" }],
});

const occupationList = ref([]); // 职业
const workEnvList = ref([]); // 工作环境
const eyeUsageDistanceList = ref([]); // 用眼距离

async function getOccupationList() {
  handleApiResponse(() => ListCustomerOccupation()).then((res) => {
    if (res.code == 0) {
      occupationList.value = res.data.list || [];
    }
  });
}
async function getWorkEnvList() {
  handleApiResponse(() => ListCustomerWorkEnv()).then((res) => {
    if (res.code == 0) {
      workEnvList.value = res.data.list || [];
    }
  });
}
async function getEyeUsageDistanceList() {
  handleApiResponse(() => ListCustomerEyeUsageDistance()).then((res) => {
    if (res.code == 0) {
      eyeUsageDistanceList.value = res.data.list || [];
    }
  });
}

const qrUrl = ref("");
// 获取登录用户信息
const userInfo = ref({});
async function getUserInfo() {
  handleApiResponse(() => GetUserInfo()).then((res) => {
    if (res.code == 0) {
      // console.log(res);
      userInfo.value = res.data;
      qrUrl.value = `https://suporev.supore.cn/jiancha?organId=${res.data.organizationId}&userId=${res.data.id}&companyName=${useStore.themeTitle}&source=pc`;
    }
  });
}

// 根据屏幕尺寸，动态控制上边距
const marginTop = ref(7);
window.addEventListener("resize", () => {
  marginTop.value = 70 / 50;
});

watch(
  () => useStore.customerInfo,
  (newVal) => {
    addForm.value = useStore.customerInfo;
  },
  { deep: true, immediate: true }
);
</script>

<style scoped lang="scss">
.change_customer {
  height: calc(100vh - 8.5rem) !important;
  @apply w-[99%] mx-auto flex justify-between items-center;

  .title {
    @apply w-full text-[var(--theme-color)] flex justify-center items-center;
  }

  .qr {
    @apply w-[30%] h-full;
  }
  .customer_info {
    @apply w-[69%] h-full;
  }

  // .ul {
  //   @apply w-full h-full flex py-[1rem];
  //   li {
  //     .title {
  //       @apply w-full h-[2rem] text-[var(--theme-color)] flex justify-center items-center;
  //     }
  //   }
  //   li:first-child {
  //     @apply w-[35%] flex flex-col  items-center;
  //     border-right: 0.1rem solid #ccc;
  //   }
  //   li:last-child {
  //     @apply w-[65%] flex-col  items-center relative;
  //     .footer {
  //       @apply w-full  absolute bottom-0 left-0 flex justify-center items-center;
  //     }
  //   }
  // }
}

.addForm {
  @apply w-[100%] mx-auto;
  .el-form-item {
    @apply w-full mb-0;
    .input {
      // @apply w-full;
    }
  }
}

.star {
  color: red;
  font-size: 0.8rem;
  margin-left: 0.3rem;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden !important;
}

:deep(.el-scrollbar__bar.is-horizontal) {
  display: none !important;
}

:deep(.el-descriptions__cell.el-descriptions__content) {
  width: 20% !important;
}
:deep(.el-descriptions__label) {
  width: 15%;
  min-width: 6rem !important;
  @apply px-1;
}
</style>